package cn.learn.server;

import java.io.IOException;
import java.net.InetSocketAddress;

public abstract class ServerCnxnFactory {

    protected ZooKeeperServer zkServer;

    public final void setZooKeeperServer(ZooKeeperServer zks) {
        this.zkServer = zks;
        if (zks != null) {
            zks.setServerCnxnFactory(this);
        }
    }

    public static ServerCnxnFactory createFactory() throws IOException {
        String serverCnxnFactoryName = NettyServerCnxnFactory.class.getName();

        try {
            ServerCnxnFactory serverCnxnFactory = (ServerCnxnFactory) Class.forName(serverCnxnFactoryName)
                    .getDeclaredConstructor()
                    .newInstance();
            return serverCnxnFactory;
        } catch (Exception e) {
            IOException ioe = new IOException("Couldn't instantiate " + serverCnxnFactoryName, e);
            throw ioe;
        }
    }

    abstract void configure(InetSocketAddress clientPortAddress) throws IOException;

    public void startup(ZooKeeperServer zkServer) {
        startup(zkServer, true);
    }

    protected abstract void startup(ZooKeeperServer zkServer, boolean startServer);

    public abstract void addSession(long sessionId, NettyServerCnxn nettyServerCnxn);
}
